package br.com.ffm.praticas.facade;

import java.sql.SQLException;

import br.com.ffm.praticas.bean.PersonType;
import br.com.ffm.praticas.dao.PersonTypeDAO;

public class PersonTypeFACADE {
	
	private static PersonTypeFACADE personTypeFACADE;
	private static PersonTypeDAO personTypeDAO;
	
	/**
	 * Constructor of PersonTypeFACADE
	 */
	private PersonTypeFACADE(){
		personTypeDAO = new PersonTypeDAO();
	}
	
	/**
	 * Method that return an unique instance of PersonTypeFACADE
	 * @return An instance of PersonTypeFACADE
	 */
	public static PersonTypeFACADE getInstance(){
		if(personTypeFACADE == null){
			personTypeFACADE = new PersonTypeFACADE();
		}
		return personTypeFACADE;
	}
	
	/**
	 * Method that test if an personType exist
	 * @param personType The PersonType to be tested
	 * @return If the personType exists returns true, else returns false
	 * @throws SQLException
	 */
	private boolean alreadyExist(PersonType personType) throws SQLException{
		if(personType != null){
			PersonType pt = personTypeDAO.getPersonType(personType.getId());
			if(pt != null){
				return true;
			} else {
				return false;
			}
		}
		return false;
	}
	
	/**
	 * Method that insert a PersonType
	 * @param personType The personType to be inserted
	 * @return If insert returns true, else returns false
	 * @throws SQLException
	 */
	public boolean insert(PersonType personType) throws SQLException{
		if(personType != null && !this.alreadyExist(personType)){
			personTypeDAO.insert(personType);
			return true;
		}
		return false;
	}
	
	/**
	 * Method that delete a PersonType
	 * @param personType The personType to be deleted
	 * @return If delete returns true
	 * @throws SQLException
	 */
	public boolean delete(PersonType personType) throws SQLException{
		if(personType != null && alreadyExist(personType)){
			personTypeDAO.delete(personType);
			return true;
		}
		return false;
	}
	
	/**
	 * Method that find and return a PersonType
	 * @param id The id of PersonType to be found
	 * @return If found return the PersonType
	 * @throws SQLException
	 */
	public PersonType getPersonType(int id) throws SQLException{
		return personTypeDAO.getPersonType(id);
	}
	
	/**
	 * Method that update a personType
	 * @param personType The personType to be updated
	 * @return If update returns true
	 * @throws SQLException
	 */
	public boolean update(PersonType personType) throws SQLException{
		if(personType != null && alreadyExist(personType)){
			personTypeDAO.update(personType);
			return true;
		}
		return false;
	}
	
}
